﻿using System;

namespace Microsoft.Popfly.GameCreator.GameEngine.Events
{
    public class CollisionEndChecker : IEventChecker
    {
        private CollisionEventArgsFilter m_argsFilter;
        private CollisionEventArgs m_args = null;
        private BehaviorOwner m_sender = null;
        public CollisionClassWithEndChecker[] CollisionClasses { get; private set; }

        public CollisionEndChecker(BehaviorOwner eventOwner, Data.EventInfo eventInfo)
        {
            Type eventType = eventInfo.GetType();
            if (eventType != typeof(Data.CollisionEventInfo))
            {
                throw new ArgumentException(
                    Utils.ErrorMessagePrefix +
                    "CollisionEndCheckers only support collision event info.  '" +
                    eventType.ToString() + "' was passed in.");
            }
            Data.CollisionEventInfo collisionEvent = (Data.CollisionEventInfo)eventInfo;

            if (collisionEvent.CollisionType != "CollisionEnd")
            {
                throw new ArgumentException(
                    Utils.ErrorMessagePrefix +
                    "CollisionEndCheckers are only meant for collision ends, not '" +
                    collisionEvent.CollisionType + "'s.");
            }

            

            CollisionClasses = new CollisionClassWithEndChecker[2];
            CollisionClasses[0] = new CollisionClassWithEndChecker(this, eventOwner, collisionEvent.Includes, collisionEvent.SubType);
            CollisionClasses[1] = new CollisionClassWithEndChecker(this, eventOwner, collisionEvent.Includes2, collisionEvent.SubType2);
            m_argsFilter = new CollisionEventArgsFilter(CollisionClasses, collisionEvent);
        }

        internal void QueueRaise(BehaviorOwner sender, CollisionEventArgs args)
        {
            m_sender = sender;
            m_args = args;
        }

        #region IEventChecker Members

        public bool FireThisFrame(double elapsedTimeInSeconds, out BehaviorOwner sender, out PGCEventArgs args)
        {
            if (m_args != null)
            {
                if (m_argsFilter.CheckArgs(m_args))
                {
                    args = m_args;
                    sender = m_sender;
                    m_args = null;
                    m_sender = null;
                    return true;
                }
                m_args = null;
                m_sender = null;
            }

            sender = null;
            args = null;
            return false;
            
        }

        public bool IsOfEventType(string eventType)
        {
            return eventType == "collision";
        }

        #endregion
    }
}
